import tkinter as tk
from json import loads
from tkinter import ttk
import asyncio
import threading
from queue import Queue
#导入mcp client
from client import MCPClient


class QueryMenu:
    def __init__(self, root):
        self.root = root
        self.root.title("Excel智能体")
        self.root.geometry("1100x600")
        
        # 初始化异步相关的变量
        self.loop = None
        self.client_ready = threading.Event()
        self.result_queue = Queue()
        # 初始化client变量，@todo
        self.client:MCPClient = None

        # 启动异步事件循环线程
        self.start_async_loop()
        
        # 创建主框架
        self.main_frame = ttk.Frame(self.root, padding="10")
        self.main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 创建查询区域
        self.search_frame = ttk.Frame(self.main_frame)
        self.search_frame.grid(row=0, column=0, pady=10, sticky=(tk.W, tk.E))
        
        # 创建文本域和查询按钮
        self.name_text = tk.Text(self.search_frame, height=3, width=50)
        self.name_text.grid(row=0, column=0, padx=5)
        
        # 添加默认提示文字
        self.placeholder = "请输入你的需求"
        self.name_text.insert("1.0", self.placeholder)
        self.name_text.config(fg='gray')
        
        # 绑定事件处理
        self.name_text.bind("<FocusIn>", self.on_focus_in)
        self.name_text.bind("<FocusOut>", self.on_focus_out)
        
        self.search_button = ttk.Button(self.search_frame, text="查询", command=self.start_search)
        self.search_button.grid(row=0, column=1, padx=5)
        
        # 创建结果显示区域
        self.result_frame = ttk.LabelFrame(self.main_frame, text="查询结果", padding="10")
        self.result_frame.grid(row=1, column=0, pady=10, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 创建表格
        self.create_result_table()
        
        # 创建进度条
        self.progress_var = tk.DoubleVar()
        self.progress = ttk.Progressbar(self.main_frame, variable=self.progress_var, mode='indeterminate')
        self.progress.grid(row=2, column=0, pady=10, sticky=(tk.W, tk.E))
        self.progress.grid_remove()  # 初始隐藏进度条

    def start_async_loop(self):
        """启动异步事件循环线程"""
        def run_async_loop():
            self.loop = asyncio.new_event_loop()
            asyncio.set_event_loop(self.loop)
            
            async def init_client():
                # 初始化MCPClient,@todo
                self.client = await MCPClient()
                self.client_ready.set()
                print("MCP客户端初始化完成")
                
            self.loop.run_until_complete(init_client())
            self.loop.run_forever()
            
        self.async_thread = threading.Thread(target=run_async_loop, daemon=True)
        self.async_thread.start()

    def create_result_table(self):
        # 创建表格显示区域
        columns = ["序号", "学生姓名", "性别", "身份证号码", "申请学校", 
                  "申请年级", "录取结果-批次", "录取结果-分数", "录取结果-录取学校", "备注"]
        
        self.tree = ttk.Treeview(self.result_frame, columns=columns, show='headings', height=10)
        
        # 设置列标题和列属性
        for col in columns:
            self.tree.heading(col, text=col, anchor='center')  # 标题居中
            self.tree.column(col, width=100, anchor='center')  # 数据居中
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(self.result_frame, orient=tk.VERTICAL, command=self.tree.yview)
        self.tree.configure(yscrollcommand=scrollbar.set)
        
        # 放置表格和滚动条
        self.tree.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))

    async def query_data(self):
        try:
            text_content = self.name_text.get("1.0", "end-1c")
            if text_content == self.placeholder:
                text_content = ""
            print("====== 用户输入的信息：", text_content)
            with open("prompt.md", "r",encoding="utf-8") as f:
                prompt = f.read()
            #替换模板中的变量
            text_content = prompt.replace("{{user_input}}", text_content)
            #调用client的execute方法，@todo
            result = await self.client.execute(text_content)
            result = loads(result)
            print("转换过的result结果:", result)
            return result
        except Exception as e:
            print(f"查询出错: {e}")
            return None

    def clear_table(self):
        for item in self.tree.get_children():
            self.tree.delete(item)

    def update_table(self, data):
        self.clear_table()
        if data:
            for row in data:
                self.tree.insert('', tk.END, values=row)

    def start_search(self):
        if not self.client_ready.is_set():
            print("客户端尚未初始化完成，请稍后重试")
            return
            
        # 清除上次的查询结果
        self.clear_table()
            
        # 显示进度条
        self.progress.grid()
        self.progress.start(10)
        
        # 禁用查询按钮
        self.search_button.state(['disabled'])
        
        async def async_execute():
            try:
                result = await self.query_data()
                # 在主线程中更新UI
                self.root.after(0, lambda: self.finish_search(result))
            except Exception as e:
                print(f"执行出错：{e}")
                self.root.after(0, lambda: self.finish_search(None))
                
        # 将任务提交到事件循环
        asyncio.run_coroutine_threadsafe(async_execute(), self.loop)

    def finish_search(self, result):
        # 停止并隐藏进度条
        self.progress.stop()
        self.progress.grid_remove()
        
        # 启用查询按钮
        self.search_button.state(['!disabled'])
        
        # 更新表格数据
        self.update_table(result)

    def on_closing(self):
        """窗口关闭时的清理操作"""
        if self.loop:
            self.loop.call_soon_threadsafe(self.loop.stop)
        self.root.destroy()

    def on_focus_in(self, event):
        if self.name_text.get("1.0", "end-1c") == self.placeholder:
            self.name_text.delete("1.0", tk.END)
            self.name_text.config(fg='black')

    def on_focus_out(self, event):
        if not self.name_text.get("1.0", "end-1c").strip():
            self.name_text.insert("1.0", self.placeholder)
            self.name_text.config(fg='gray')

def main():
    root = tk.Tk()
    app = QueryMenu(root)
    root.protocol("WM_DELETE_WINDOW", app.on_closing)  # 设置窗口关闭处理
    root.mainloop()

if __name__ == "__main__":
    main()



